package com.app.island.cash.wegit

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import com.app.island.cash.R
import java.util.*

class TimeDownButton : AppCompatTextView {
    /** 倒计时长，默认60秒  */
    private var length = (60 * 1000).toLong()

    /** 按钮初始化时显示的内容  */
    private var textInit = ""
    private var isInit = false

    /** enable时显示的内容  */
    private var textBefore = "GET"

    /** disable时显示的内容  */
    private var textAfter = "s Resend"
    //    /** TimeButton的点击监听 */
    //    private OnClickListener mOnclickListener;
    /** 状态被复位的通知  */
    private var mCallback: ResetCallback? = null
    private var timer: Timer? = null
    private var timerTask: TimerTask? = null

    /** 倒计时时间  */
    private var time: Long = 0

    /** onDestroy()时，倒计时剩余时间  */
    private var timeStr: String? = null

    /** onDestroy()时，系统时间  */
    private var currentTimeStr: String? = null

    constructor(context: Context?) : super(context!!) {
        textInit = this.text.toString()
        //        setOnClickListener(this);
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(
        context!!, attrs
    ) {
        textInit = this.text.toString()
        //        setOnClickListener(this);
    }

    @SuppressLint("HandlerLeak")
    var han: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            if (!isInit) {
                this@TimeDownButton.text = (time / 1000).toString() + textAfter
                time -= 1000
                if (time < 0) {
                    reset()
                }
            }
        }
    }

    /**
     * 初始化定时器
     */
    private fun initTimer() {
        time = length
        timer = Timer()
        timerTask = object : TimerTask() {
            override fun run() {
                han.sendEmptyMessage(0x01)
            }
        }
    }

    /**
     * 清除计时器
     */
    fun clearTimer() {
        if (timer != null) {
            timer!!.cancel()
            timer = null
        }
        if (timerTask != null) {
            timerTask!!.cancel()
            timerTask = null
        }
        time = 0
    }

    /**
     * 设置复位监听
     */
    fun setResetCallback(callback: ResetCallback?) {
        mCallback = callback
    }

    override fun setEnabled(enabled: Boolean) {
        if (!enabled || isClickable) {
            super.setEnabled(enabled)
        }
    }

    fun runTimer() {
        initTimer()
        this.text = (time / 1000).toString() + textAfter
        this.isClickable = false
        this.isEnabled = false
        this.isFocusable = false
        isInit = false
        timer!!.schedule(timerTask, 0, 1000)
        // timer.scheduleAtFixedRate(task, delay, period);
        this.setTextColor(ContextCompat.getColor(context, R.color.color_26357b))
    }

    /**
     * 和activity的onCreate()方法同步
     */
    fun onCreate(activity: Activity) {
        timeStr = activity.javaClass.simpleName + "_time"
        currentTimeStr = activity.javaClass.simpleName + "_ctime"
        // 这里表示没有上次未完成的计时
        if (map == null || !map!!.containsKey(timeStr) || !map!!.containsKey(currentTimeStr)) return
        val time = System.currentTimeMillis() - map!![currentTimeStr]!! - map!![timeStr]!!
        map!!.remove(timeStr)
        map!!.remove(currentTimeStr)
        if (time > 0) {
            // TODO
        } else {
            initTimer()
            this.time = Math.abs(time)
            timer!!.schedule(timerTask, 0, 1000)
            this.text = time.toString() + textAfter
            this.setTextColor(ContextCompat.getColor(context, R.color.color_26357b))
            this.isClickable = false
            this.isEnabled = false
            this.isFocusable = false
        }
    }

    /**
     * 和activity的onDestroy()方法同步
     */
    fun onDestroy() {
        if (map == null) map = HashMap()
        map!![timeStr] = time
        map!![currentTimeStr] = System.currentTimeMillis()
        clearTimer()
    }

    /**
     * 设置点击之前的文本
     *
     * @param textBefore
     * 点击之前的文本
     *
     * @return TimeButton
     */
    fun setTextBefore(textBefore: String): TimeDownButton {
        this.textBefore = textBefore
        return this
    }

    /**
     * 设置计时时显示的文本
     *
     * @param textAfter
     * 计时时显示的文本
     *
     * @return TimeButton
     */
    fun setTextAfter(textAfter: String): TimeDownButton {
        this.textAfter = textAfter
        return this
    }

    /**
     * 设置倒计时时长
     *
     * @param length
     * 时间 默认毫秒
     *
     * @return TimeButton
     */
    fun setLength(length: Long): TimeDownButton {
        this.length = length
        return this
    }

    /**
     * 获得倒计时时间
     *
     * @return TimeButton
     */
    fun getTime(): Long {
        return time / 1000
    }

    /**
     * 复位
     */
    fun reset() {
        this.isClickable = true
        this.isEnabled = true
        this.isFocusable = true
        this.text = textBefore
        this.setTextColor(ContextCompat.getColor(context, R.color.btn_otp_text_color))
        clearTimer()
        if (null != mCallback) {
            mCallback!!.reset()
        }
    }

    /**
     * 初始化按钮
     */
    fun init() {
        this.isClickable = true
        this.isEnabled = true
        this.isFocusable = true
        this.text = textInit
        isInit = true
        this.setTextColor(ContextCompat.getColor(context, R.color.btn_otp_text_color))
        clearTimer()
        if (null != mCallback) {
            mCallback!!.reset()
        }
    }

    /**
     * 初始化按钮
     */
    fun start() {
        initTimer()
        time = Math.abs(time)
        timer!!.schedule(timerTask, 0, 1000)
        this.text = time.toString() + textAfter
        this.setTextColor(ContextCompat.getColor(context, R.color.color_26357b))
        this.isClickable = false
        this.isEnabled = false
        this.isFocusable = false
    }

    interface ResetCallback {
        fun reset()
    }

    companion object {
        private var map: MutableMap<String?, Long>? = HashMap()
    }
}